/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.biz.service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.modules.biz.dao.BizBarcodeDao;
import com.thinkgem.jeesite.modules.biz.dao.BizGoodsDao;
import com.thinkgem.jeesite.modules.biz.dao.BizStorageLocationDao;
import com.thinkgem.jeesite.modules.biz.entity.BizBarcode;
import com.thinkgem.jeesite.modules.biz.entity.BizGoods;
import com.thinkgem.jeesite.modules.biz.entity.BizStorageLocation;
import com.thinkgem.jeesite.modules.biz.form.BizStockLogListForm;
import com.thinkgem.jeesite.modules.biz.form.BizStockLogSaveForm;
import com.thinkgem.jeesite.modules.biz.vo.BizStockLogVo;
import com.thinkgem.jeesite.modules.biz.vo.ResultVO;
import com.thinkgem.jeesite.modules.sys.dao.UserDao;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.enums.ResultEnum;
import com.thinkgem.jeesite.modules.sys.utils.AutoNameUtils;
import com.thinkgem.jeesite.modules.sys.utils.ResultVOUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.modules.biz.entity.BizStockLog;
import com.thinkgem.jeesite.modules.biz.dao.BizStockLogDao;

/**
 * 期出期入的logService
 * @author tiancheng
 * @version 2018-09-13
 */
@Service
@Transactional(readOnly = true)
public class BizStockLogService extends CrudService<BizStockLogDao, BizStockLog> {

	@Autowired
	private BizStockLogDao bizStockLogDao;
	@Autowired
	private BizBarcodeDao bizBarcodeDao;
	@Autowired
	private BizGoodsDao bizGoodsDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private BizStorageLocationDao bizStorageLocationDao;

	public BizStockLog get(String id) {
		return super.get(id);
	}
	
	public List<BizStockLog> findList(BizStockLog bizStockLog) {

		return super.findList(bizStockLog);
	}

	 /**
	  * 手机端查询期初期入的列表
	  * @author tiancheng  
	  * @date 2018/9/13 14:29
	  * @param
	  * @return   
	  */  
	public List<BizStockLogVo> findListApi(BizStockLogListForm bizStockLogListForm) {
		BizStockLog bizStockLog = new BizStockLog();
		bizStockLog.setPageSize(bizStockLogListForm.getPageSize());
		bizStockLog.setPageNo((bizStockLogListForm.getPageNo()-1)*bizStockLogListForm.getPageSize());
		return bizStockLogDao.findListApi(bizStockLog);
	}
	
	public Page<BizStockLog> findPage(Page<BizStockLog> page, BizStockLog bizStockLog) {
		return super.findPage(page, bizStockLog);
	}
	
	 /**
	  *  手机端的期初期入
	  * @author tiancheng  
	  * @date 2018/9/13 10:30
	  * @param
	  * @return   
	  */  
	@Transactional(readOnly = false)
	public ResultVO save(BizStockLogSaveForm bizStockLogSaveForm) {
		BizStockLog bizStockLog = new BizStockLog();
		bizStockLog.setNumber(bizStockLogSaveForm.getNumber());
		String name = AutoNameUtils.createAutoNameByTableName("biz_stock_log");
		bizStockLog.setName(name);
		BizGoods bizGoods = new BizGoods();
		//判断是期初还是期入
		if(null != bizStockLogSaveForm.getTypeInfo() &&
				(bizStockLogSaveForm.getTypeInfo().equals("1") || bizStockLogSaveForm.getTypeInfo().indexOf("3") != -1)){
			//酱料的期出期入
			//获取条码的信息
			BizBarcode bizBarcode = bizBarcodeDao.getByName(bizStockLogSaveForm.getBarcode());
			bizGoods = bizGoodsDao.selectInfoByGoodsCode(bizStockLogSaveForm.getGoodsCode());
			if(bizStockLogSaveForm.getTypeInfo().equals("32")){//32 为编号的期入（不涉及到条码，需要重新生成）
				//判断输入的商品编号是否存在
				if(null == bizGoods || null == bizGoods.getGoodsId()){
					return ResultVOUtil.error(ResultEnum.PRODUCT_NOT_EXIST.getCode(),"商品不存在！");
				}
				//添加日志
				bizStockLog.setGoodsId(bizGoods.getGoodsId());
				bizStockLog.setStorageLocationId(bizStockLogSaveForm.getStorageLocationId());
				BizStorageLocation bizStorageLocation = bizStorageLocationDao.get(bizStockLogSaveForm.getStorageLocationId());
				bizStockLog.setStorageLocationName(bizStorageLocation.getName());
				bizStockLog.setGoodsName(bizGoods.getGoodsName());

				bizGoods.setGoodsId(bizGoods.getGoodsId());
			}else{
				//添加日志
				bizStockLog.setGoodsId(bizBarcode.getGoodsId());
				bizStockLog.setGoodsName(bizBarcode.getGoodsName());
				bizStockLog.setStorageLocationId(bizBarcode.getStorageLocationId());
				bizStockLog.setStorageLocationName(bizBarcode.getStorageLocationName());

				bizGoods.setGoodsId(bizBarcode.getGoodsId());
			}

			//判断是期初还是期入
			if(bizStockLogSaveForm.getTypeInfo().equals("1")){//期初
				//减库存
				if(Integer.valueOf(bizBarcode.getStockAmount()) < Integer.valueOf(bizStockLogSaveForm.getNumber())){
					return ResultVOUtil.error(ResultEnum.PRODUCT_STOCK_ERROR.getCode(),"当前库存不足！");
				}
				Integer cha = Integer.valueOf(bizGoods.getStockAmount()) - Integer.valueOf(bizStockLogSaveForm.getNumber());
				Integer sureCha = Integer.valueOf(bizGoods.getSureStockAmount()) - Integer.valueOf(bizStockLogSaveForm.getNumber());

				bizStockLog.setType("0");
				bizStockLog.setStockAmountFront(bizGoods.getStockAmount().toString());
				bizStockLog.setStockAmountAfter(cha.toString());

				bizGoods.setStockAmount(cha);
				bizGoods.setSureStockAmount(sureCha);

				//修改条码的数量
				//判断当前条码上的数量
				if(Integer.valueOf(bizBarcode.getNumber()) < Integer.valueOf(bizStockLogSaveForm.getNumber())){
					return ResultVOUtil.error(ResultEnum.BARCODE_NUMBER.getCode(),"托盘上商品数量不足！");
				}
				Integer num = Integer.valueOf(bizBarcode.getNumber()) - Integer.valueOf(bizStockLogSaveForm.getNumber());//实际数量
				Integer surNum = Integer.valueOf(bizBarcode.getNumber()) - Integer.valueOf(bizStockLogSaveForm.getNumber());//可用库存
				bizBarcode.setNumber(num.toString());
				bizBarcode.setSurplusNumber(surNum.toString());
				if(num == 0){
					bizBarcode.setDelFlag("1");
				}
				bizBarcodeDao.update(bizBarcode);
			}else if(bizStockLogSaveForm.getTypeInfo().indexOf("3") != -1){//期入
				bizStockLog.setType("1");
				Integer he = 0;  // 库存数
				Integer sureHe = 0;  // 可用库存数
				if(bizStockLogSaveForm.getTypeInfo().equals("31")){//扫码期入
					//加库存
					he = Integer.valueOf(bizGoods.getStockAmount()) + Integer.valueOf(bizStockLogSaveForm.getNumber());
					sureHe = Integer.valueOf(bizGoods.getSureStockAmount()) + Integer.valueOf(bizStockLogSaveForm.getNumber());

					bizStockLog.setStockAmountFront(bizGoods.getStockAmount().toString());
					bizStockLog.setStockAmountAfter(he.toString());

					//修改条码的数量
					Integer num = Integer.valueOf(bizBarcode.getNumber()) + Integer.valueOf(bizStockLogSaveForm.getNumber());//实际库存
					Integer surNum = Integer.valueOf(bizBarcode.getSurplusNumber()) + Integer.valueOf(bizStockLogSaveForm.getNumber());//可用库存
					bizBarcode.setNumber(num.toString());
					bizBarcode.setSurplusNumber(surNum.toString());
					bizBarcodeDao.update(bizBarcode);

				}else if(bizStockLogSaveForm.getTypeInfo().equals("32")){//商品编号期初
					//加库存
					he = Integer.valueOf(bizGoods.getStockAmount()) + Integer.valueOf(bizStockLogSaveForm.getNumber());
					sureHe = Integer.valueOf(bizGoods.getSureStockAmount()) + Integer.valueOf(bizStockLogSaveForm.getNumber());

					bizStockLog.setStockAmountFront(bizGoods.getStockAmount().toString());
					bizStockLog.setStockAmountAfter(he.toString());

					//只有酱料和冷链生成条码
					if(null != bizStockLogSaveForm.getGoodsCode() && (
							bizStockLogSaveForm.getGoodsCode().substring(0,1).equals("J")
							|| bizStockLogSaveForm.getGoodsCode().substring(0,1).equals("L")
							)){
						bizStockLog.setIsTm("1");  //商品编号期入需要生成条码
					}

					//生成条码(只生成信息，条码的生成在pc端)
					SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
					SimpleDateFormat si = new SimpleDateFormat("yyMMdd");
					//app端传输年月日乱码，需要解密
					String manufactureDate = null;
					String manufactureDateSAve = null;
					try {
						manufactureDate = URLDecoder.decode(bizStockLogSaveForm.getManufactureDate(), "utf-8");
						manufactureDateSAve = manufactureDate;
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					manufactureDate = manufactureDate.replaceAll("年","-");
					manufactureDate = manufactureDate.replaceAll("月","-");
					manufactureDate = manufactureDate.replaceAll("日","");
					String dayinDate = "";
					try {
						dayinDate = si.format(sim.parse(manufactureDate));
					} catch (ParseException e) {
						e.printStackTrace();
					}
					//查询该生产日期下的商品是第几波生产条码
					BizBarcode barcode = new BizBarcode();
					barcode.setGoodsId(bizGoods.getGoodsId());
					barcode.setManufactureDate(manufactureDateSAve);
					//生成条形码(商品的编号+年月日(生产日期)+打印批次)
					Integer num = bizBarcodeDao.selectCountByGoodsId(barcode);
					num += 1;
					String autoNum = num.toString();
					while (autoNum.length() < 4) {
						autoNum = "0" + autoNum;
					}
					//生成条码的编号
					String code = bizGoods.getGoodsCode()+dayinDate+autoNum;

					bizBarcode = new BizBarcode();
					String id = IdGen.uuid();
					bizBarcode.setId(id);
					bizBarcode.setName(code);
					bizBarcode.setGoodsId(bizGoods.getGoodsId());
					bizBarcode.setManufactureDate(manufactureDateSAve);
					bizBarcode.setStorageLocationId(bizStockLogSaveForm.getStorageLocationId());
					//添加货区的name
					if(null != bizStockLogSaveForm.getStorageLocationId()){
						BizStorageLocation bizStorageLocation = bizStorageLocationDao.get(bizStockLogSaveForm.getStorageLocationId());
						if(null != bizStorageLocation){
							bizBarcode.setStorageLocationName(bizStorageLocation.getName()); //库位name
                            barcode.setStorageLocationName(bizStorageLocation.getName()); //库位name
						}
					}
					bizBarcode.setNumber(bizStockLogSaveForm.getNumber());
					bizBarcode.setWaitNumber("0");
					bizBarcode.setSurplusNumber(bizStockLogSaveForm.getNumber());
					User user = userDao.get(bizStockLogSaveForm.getUserId());
					bizBarcode.setCreateBy(user);
					bizBarcode.setCreateDate(new Date());
					bizBarcodeDao.insert(bizBarcode);
					//添加日志关联的条码
					bizStockLog.setBarcodeId(id);
				}

				bizGoods.setStockAmount(he);
				bizGoods.setSureStockAmount(sureHe);
			}
			//修改商品的库存
			bizGoodsDao.updateStockAmount(bizGoods);

		}else if(null != bizStockLogSaveForm.getTypeInfo() &&
				(bizStockLogSaveForm.getTypeInfo().equals("2") || bizStockLogSaveForm.getTypeInfo().equals("4"))){
			//标配的期出期入
			//查询标配
			bizGoods.setGoodsCode(bizStockLogSaveForm.getGoodsCode());
			List<BizGoods> goodsList = bizGoodsDao.findList(bizGoods);
			if(null == goodsList || goodsList.size() == 0){
				return ResultVOUtil.error(ResultEnum.PRODUCT_NOT_EXIST.getCode(),"商品不存在！");
			}
			bizGoods = goodsList.get(0);

			bizStockLog.setGoodsId(bizGoods.getGoodsId());
			bizStockLog.setGoodsName(bizGoods.getGoodsName());
			//判断是期出还是期入
			if(bizStockLogSaveForm.getTypeInfo().equals("2")){//期初
				//减库存
				if(Integer.valueOf(bizGoods.getStockAmount()) < Integer.valueOf(bizStockLogSaveForm.getNumber())){
					return ResultVOUtil.error(ResultEnum.PRODUCT_STOCK_ERROR.getCode(),"当前库存不足！");
				}
				Integer cha = bizGoods.getStockAmount() - Integer.valueOf(bizStockLogSaveForm.getNumber());
				Integer sureCha = bizGoods.getSureStockAmount() - Integer.valueOf(bizStockLogSaveForm.getNumber());

				bizStockLog.setType("0");
				bizStockLog.setStockAmountFront(bizGoods.getStockAmount().toString());
				bizStockLog.setStockAmountAfter(cha.toString());

				bizGoods.setStockAmount(cha);
				bizGoods.setSureStockAmount(sureCha);

			}else if(bizStockLogSaveForm.getTypeInfo().equals("4")){//期入
				//加库存
				Integer he = bizGoods.getStockAmount() + Integer.valueOf(bizStockLogSaveForm.getNumber());
				Integer sureHe = bizGoods.getSureStockAmount() + Integer.valueOf(bizStockLogSaveForm.getNumber());

				bizStockLog.setType("1");
				bizStockLog.setStockAmountFront(bizGoods.getStockAmount().toString());
				bizStockLog.setStockAmountAfter(he.toString());

				bizGoods.setStockAmount(he);
				bizGoods.setSureStockAmount(sureHe);
			}
			bizGoodsDao.updateStockAmount(bizGoods);
		}
		//添加操作日志
		User user = new User();
		user.setId(bizStockLogSaveForm.getUserId());
		bizStockLog.setCreateBy(user);
		bizStockLog.setUpdateBy(user);
		super.save(bizStockLog);

		return ResultVOUtil.success();
	}
	
	@Transactional(readOnly = false)
	public void delete(BizStockLog bizStockLog) {
		super.delete(bizStockLog);
	}
	
}